// 云函数入口文件
const cloud = require('wx-server-sdk')

// 云函数初始化，必须放在第一个执行
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 引入数据库实例
const db = cloud.database()
const comm = db.command
const MAX_LIMIT = 100



// 保存订单
async function saveOrder(args) {
  console.log(args)
  // 1.保存订单实体类
  db.collection("ordercoll").add({
    data: args
  });
  // 2.删除购物车
  const buycarIds = args.productList.map(item => item.buycarId);
  db.collection("buycar").where({
    _id : comm.in(buycarIds)
  }).remove();
}

/**
 * 查询所有订单
 * @param {*} args#status  状态
 * @param {*} args#openid  用户id
 */
async function findList(args) {
  // 过滤参数
  let filter = {}
  if(!args.isAdmin) {
    filter.openid = args.openid;
  }
  if(args.status != 'all') {
    filter.status = args.status
  }
  
  // 先取出集合记录总数
  const countResult = await db.collection('ordercoll').where(filter).count()
  console.log("拆线呢数据库", countResult, args)
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('ordercoll').where(filter).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  if(tasks.length === 0) {
    return {
      data: [],
      errMsg: 'ok',
    }
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}

/**
 * 取消订单
 * @param {*} event 
 * @param {*} context 
 */
async function cancelOrder(args) {
  return await db.collection("ordercoll").doc(args._id).update({
    data: {
      status: '已取消'
    }
  });
}

async function sendGoods(args) {
  return await db.collection("ordercoll").doc(args._id).update({
    data: {
      status: '配送中',
      expressNo: args.expressNo
    }
  });
}

async function getOrderById(args) {
 return await db.collection("ordercoll").doc(args._id).get();
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {method, args} = event;
  let res = null;

  if(method === "saveOrder") {
    args.openid = wxContext.OPENID
    res = await saveOrder(args);
  }else if(method === "findList") {
    args.openid = wxContext.OPENID
    res = await findList(args);
  }else if(method === "cancelOrder") {
    res = await cancelOrder(args);
  }else if(method === "sendGoods") {
    res = await sendGoods(args);
  }else if(method === "getOrderById") {
    res = await getOrderById(args);
  }

  return {
    rstData: res,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}